package com.wcr.school.controller;

import com.wcr.school.pojo.Admin;
import com.wcr.school.pojo.Login;
import com.wcr.school.pojo.Student;
import com.wcr.school.pojo.Teacher;
import com.wcr.school.service.AdminService;
import com.wcr.school.service.StudentService;
import com.wcr.school.service.TeacherService;
import com.wcr.school.util.CreateVerifiCodeImage;
import com.wcr.school.util.JwtHelper;
import com.wcr.school.util.Result;
import com.wcr.school.util.ResultCodeEnum;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/sms/system")
public class SystemController {
    @Autowired
    AdminService adminService;
    @Autowired
    StudentService studentService;
    @Autowired
    TeacherService teacherService;


    @GetMapping("/getInfo")
    public Result getInfoByToken(@RequestHeader("token") String token){
        boolean expiration = JwtHelper.isExpiration(token);
        //从token中解析出用户id和用户类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        if(expiration){
            return  Result.build(null, ResultCodeEnum.TOKEN_ERROR);

        }
        Map<String,Object> map = new LinkedHashMap<>();
        switch(userType){
            case 1:
                Admin admin = adminService.getAdminById(userId);
                map.put("userType",1);
                map.put("user",admin);
                break;
            case 2:
                Student student = studentService.getStudentById(userId);
                map.put("userType",2);
                map.put("user",student);
                break;
            case 3:
                Teacher teacher = teacherService.getTeacherById(userId);
                map.put("userType",3);
                map.put("user",teacher);
                break;
        }
        return Result.ok(map);
    }

    @PostMapping("/login")
    public Result login(@RequestBody Login login,
                        HttpServletRequest request){
        //验证码类型校验
        //用户名类型校验
        HttpSession session = request.getSession();
        String sessionVerifyCode = (String)session.getAttribute("verifyCode");
        String loginVerifyCode = login.getVerifiCode();
        System.out.println(login);
        if("".equals(sessionVerifyCode) || null == sessionVerifyCode){
            return Result.fail().message("验证码失效,请刷新后重试");
        }
        if (!sessionVerifyCode.equalsIgnoreCase(loginVerifyCode)){
            return Result.fail().message("验证码有误,请小心输入后重试");
        }
        // 从session域中移除现有验证码
        session.removeAttribute("verifyCode");
        //准备一个map存放用户响应的数据
        Map<String ,Object> map = new LinkedHashMap<>();
        switch (login.getUserType()){
            case 1:
                try {
                    Admin admin = adminService.login(login);
                    if(admin!=null){
                        map.put("token", JwtHelper.createToken(admin.getId().longValue(),1));
                    }else{
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case 2:
                try {
                    Student student = studentService.login(login);
                    if(student!=null){
                        map.put("token", JwtHelper.createToken(student.getId().longValue(),2));
                    }else{
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case 3:
                try {
                    Teacher teacher = teacherService.login(login);
                    if(teacher!=null){
                        map.put("token", JwtHelper.createToken(teacher.getId().longValue(),3));
                    }else{
                        throw new RuntimeException("用户名或者密码有误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }

        return Result.fail("没有此用户");

    }



    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
//        获取图片
//        获取图片上的验证码
//        文本放入session域
        BufferedImage verifyCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        String verifyCode = new String(CreateVerifiCodeImage.getVerifiCode());
        HttpSession session = request.getSession();
        session.setAttribute("verifyCode",verifyCode);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(verifyCodeImage,"JPEG",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation("传入保存一个图像")
    @PostMapping("/headerImgUpload")
    public Result headImaUpload(
            @ApiParam("传入图片的参数") @RequestPart("multipartFile")MultipartFile multipartFile,
            HttpServletRequest request
            )
    {
        //给图片一个随机的uuid
        String uuid = UUID.randomUUID().toString().replace("-","").toLowerCase();
        int i = multipartFile.getOriginalFilename().lastIndexOf(".");
        String newFileName = uuid+multipartFile.getOriginalFilename().substring(i);
        //图像得真实路径，在服务器上面target
        String realPath = "D:/school/target/classes/public/upload/"+newFileName;
        try {
            multipartFile.transferTo(new File(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //图片的响应路径
        String path = "/upload/"+newFileName;
        return Result.ok(path);
    }

}
